﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CourseScheduling.DataAccess;

namespace CourseScheduling
{
    public partial class CoursePreference : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                initNew();

                string id = Request.QueryString["id"];
                if (id != null)
                {
                    // If we have an emergency call then use it to fill
                    // the form with its data.
                    //
                    initUsing(id);
                }
                LoadCurrentState();
            }

            AddPreferenceRows();
        }

        private void initNew()
        {
            var mgr = Application["CSDataManager"] as CSDataManager;

            // Init year
            //
            int nCurYear = DateTime.Now.Year;
            for (int i = 0; i < 4; ++i)
            {
                var item = new ListItem(nCurYear.ToString(), nCurYear.ToString());
                ddlYear.Items.Add(item);
                ++nCurYear;
            }

            // Init courses
            //
            var courses = mgr.getCourses();
            foreach (var course in courses)
            {
                var item = new ListItem(course.Code + " - " + course.Description,
                                        course.Code);
                ddlCourses.Items.Add(item);
            }
        }

        private void initUsing(string id)
        {
            var mgr = Application["CSDataManager"] as CSDataManager;

            int nId = -1;
            if (!int.TryParse(id, out nId))
            {
                return;     // no conversion; get out of dodge
            }
            var profPrefs = mgr.getProfRequests(nId);
            if (profPrefs.Count < 1)
            {
                return;     // no find; get out of dodge
            }

            lblProfPrefId.Text = id;

            var profPref = profPrefs[0];
            Session["ddlTerm"] = profPref.Semester;
            Session["ddlCourseRelease"] = profPref.CourseRelease ? "Yes" : "No";
            Session["ddlSabbatical"] = profPref.Sabbatical ? "Yes" : "No";
            Session["ddlYear"] = profPref.Year.ToString();
            Session["ddlCourseNum"] = profPref.NumCourses.ToString();
            Session["ddlLeave"] = profPref.Leave ? "Yes" : "No";
            Session["ddlCoursePreference"] = profPref.CourseRank.ToString();
            Session["ddlDaysOfWeek"] = profPref.DayOfWeekRank.ToString();
            Session["ddlTimeOfDay"] = profPref.TimeOfDayRank.ToString();
            Session["ddlMorning"] = profPref.MorningRank.ToString();
            Session["ddlAfternoon"] = profPref.AfternoonRank.ToString();
            Session["ddlEvening"] = profPref.EveningRank.ToString();
            Session["lblProfPrefId"] = id;

            Session["CoursePreferences"] = mgr.getCoursePreference(nId);
        }

        protected void SaveCurrentState()
        {
            Session["ddlTerm"] = ddlTerm.SelectedValue;
            Session["ddlCourseRelease"] = ddlCourseRelease.SelectedValue;
            Session["ddlSabbatical"] = ddlSabbatical.SelectedValue;
            Session["ddlYear"] = ddlYear.SelectedValue;
            Session["ddlCourseNum"] = ddlCourseNum.SelectedValue;
            Session["ddlCourses"] = ddlCourses.SelectedValue;
            Session["ddlLeave"] = ddlLeave.SelectedValue;
            Session["ddlCoursePreference"] = ddlCoursePreference.SelectedValue;
            Session["ddlDaysOfWeek"] = ddlDaysOfWeek.SelectedValue;
            Session["ddlTimeOfDay"] = ddlTimeOfDay.SelectedValue;
            Session["ddlMorning"] = ddlMorning.SelectedValue;
            Session["ddlAfternoon"] = ddlAfternoon.SelectedValue;
            Session["ddlEvening"] = ddlEvening.SelectedValue;
            Session["lblProfPrefId"] = lblProfPrefId.Text;
        }

        protected void LoadCurrentState()
        {
            string str = Session["ddlTerm"] as string;
            if (!string.IsNullOrEmpty(str))
            {
                ddlTerm.SelectedValue = str;
            }

            str = Session["ddlCourseRelease"] as string;
            if (!string.IsNullOrEmpty(str))
            {
                ddlCourseRelease.SelectedValue = str;
            }

            str = Session["ddlSabbatical"] as string;
            if (!string.IsNullOrEmpty(str))
            {
                ddlSabbatical.SelectedValue = str;
            }

            str = Session["ddlYear"] as string;
            if (!string.IsNullOrEmpty(str))
            {
                // TODO: check year in list; if not add
                ddlYear.SelectedValue = str;
            }

            str = Session["ddlCourseNum"] as string;
            if (!string.IsNullOrEmpty(str))
            {
                ddlCourseNum.SelectedValue = str;
            }

            str = Session["ddlCourses"] as string;
            if (!string.IsNullOrEmpty(str))
            {
                ddlCourses.SelectedValue = str;
            }

            str = Session["ddlLeave"] as string;
            if (!string.IsNullOrEmpty(str))
            {
                ddlLeave.SelectedValue = str;
            }

            str = Session["ddlCoursePreference"] as string;
            if (!string.IsNullOrEmpty(str))
            {
                ddlCoursePreference.SelectedValue = str;
            }

            str = Session["ddlDaysOfWeek"] as string;
            if (!string.IsNullOrEmpty(str))
            {
                ddlDaysOfWeek.SelectedValue = str;
            }
            
            str = Session["ddlTimeOfDay"] as string;
            if (!string.IsNullOrEmpty(str))
            {
                ddlTimeOfDay.SelectedValue = str;
            }

            str = Session["ddlMorning"] as string;
            if (!string.IsNullOrEmpty(str))
            {
                ddlMorning.SelectedValue = str;
            }
            
            str = Session["ddlAfternoon"] as string;
            if (!string.IsNullOrEmpty(str))
            {
                ddlAfternoon.SelectedValue = str;
            }
            
            str = Session["ddlEvening"] as string;
            if (!string.IsNullOrEmpty(str))
            {
                ddlEvening.SelectedValue = str;
            }

            str = Session["lblProfPrefId"] as string;
            if (!string.IsNullOrEmpty(str))
            {
                lblProfPrefId.Text = str;
            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            var prefs = Session["CoursePreferences"] as List<CSCoursePreference>;
            if (prefs == null)
            {
                // This should never happen but it is better to be safe
                // than sorry.
                //
                Session["CoursePreferences"] = new List<CSCoursePreference>();
            }

            var pref = new CSCoursePreference();
            pref.CourseCode = ddlCourses.SelectedValue;

            bool bFound = false;
            foreach (var pref2 in prefs)
            {
                if (string.Compare(pref2.CourseCode, ddlCourses.SelectedValue, true) == 0)
                {
                    bFound = true;
                    break;
                }
            }

            if (!bFound)
            {
                prefs.Add(pref);

                // Re-rank all in order
                //
                int rowId = 0;
                foreach (var p in prefs)
                {
                    p.Rank = rowId + 1;
                    ++rowId;
                }

                SaveCurrentState();
                Response.Redirect(Request.Path);
            }
        }

        protected void AddPreferenceRows()
        {
            var prefs = Session["CoursePreferences"] as List<CSCoursePreference>;

            // Get the data manager from the application
            //
            var mgr = Application["CSDataManager"] as CSDataManager;

            foreach (var pref in prefs)
            {
                var row = new TableRow();

                // Rank
                //
                var cell = new TableCell();
                cell.Text = pref.Rank.ToString();
                row.Cells.Add(cell);

                // Course number
                //
                cell = new TableCell();
                cell.Text = pref.CourseCode;
                row.Cells.Add(cell);

                // Course name
                //
                var course = mgr.getCourse(pref.CourseCode);

                cell = new TableCell();
                if (course != null)
                {
                    cell.Text = course.Description;
                }
                row.Cells.Add(cell);

                // Command
                //
                cell = new TableCell();
                cell.HorizontalAlign = HorizontalAlign.Center;

                var button = new Button();
                button.CommandArgument = pref.CourseCode;
                button.Click += Delete_OnClick;
                button.Text = "Delete";

                cell.Controls.Add(button);
                row.Cells.Add(cell);

                tblPreferences.Rows.Add(row);
            }
        }

        protected void Delete_OnClick(object sender, EventArgs e)
        {
            var prefs = Session["CoursePreferences"] as List<CSCoursePreference>;
            var button = sender as Button;
            var strCourseCode = button.CommandArgument;

            var removePrefs = new List<CSCoursePreference>();
            foreach (var pref in prefs)
            {
                if (string.Compare(pref.CourseCode, strCourseCode, true) == 0)
                {
                    removePrefs.Add(pref);
                }
            }

            foreach (var pref in removePrefs)
            {
                prefs.Remove(pref);
            }

            Response.Redirect(Request.Path);
        }

        private bool GetSafeBool(string str)
        {
            bool bRet = false;
            bool.TryParse(str, out bRet);
            return bRet;
        }

        private int GetSafeInt(string str)
        {
            int nInt = -1;
            int.TryParse(str, out nInt);
            return nInt;
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            var prefs = Session["CoursePreferences"] as List<CSCoursePreference>;
            var mgr = Application["CSDataManager"] as CSDataManager;

            bool bIsEditing = false;
            int id = -1;
            if (!string.IsNullOrEmpty(lblProfPrefId.Text))
            {
                id = int.Parse(lblProfPrefId.Text);
                bIsEditing = true;
            }

            var profPref = new CSProfessorPreference();
            profPref.NNumber = User.Identity.Name;
            profPref.Semester = ddlTerm.SelectedValue;
            profPref.CourseRelease = GetSafeBool(ddlCourseRelease.SelectedValue);
            profPref.Sabbatical = GetSafeBool(ddlSabbatical.SelectedValue);
            profPref.Year = GetSafeInt(ddlYear.SelectedValue);
            profPref.NumCourses = GetSafeInt(ddlCourseNum.SelectedValue);
            profPref.Leave = GetSafeBool(ddlLeave.SelectedValue);
            profPref.CourseRank = GetSafeInt(ddlCoursePreference.SelectedValue);
            profPref.DayOfWeekRank = GetSafeInt(ddlDaysOfWeek.SelectedValue);
            profPref.TimeOfDayRank = GetSafeInt(ddlTimeOfDay.SelectedValue);
            profPref.MorningRank = GetSafeInt(ddlMorning.SelectedValue);
            profPref.AfternoonRank = GetSafeInt(ddlAfternoon.SelectedValue);
            profPref.EveningRank = GetSafeInt(ddlEvening.SelectedValue);
            profPref.Date = DateTime.Now;

            int prefId = id;
            if (!bIsEditing)
            {
                prefId = mgr.createProfPref(profPref);
            }
            else
            {
                mgr.updateProfPref(prefId, profPref);
                mgr.deleteCoursePreference(prefId);
            }

            foreach (var pref in prefs)
            {
                pref.ProfPreferenceID = prefId;
                pref.Remove("CourseRankID");    // auto-number, never set it
                mgr.createCoursePreference(pref);
            }

            Response.Redirect("CoursePreferenceConfirmation.aspx");
        }
    }
}